// 引入此文件需自建如下内容：
// footerButtons
import { transferDataDetail } from '@/components/task/utils';
import { PLAN_TYPE } from '@/constants';
import { mapGetters } from 'vuex';
import ColumnsTooltip from '../components/columnsTooltip.vue';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    formInfo: {
      type: Object,
      default: () => ({}),
    },
    visibled: {
      type: Boolean,
      default: false,
    },
    hasEdit: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => [],
    },
    detail: {
      type: Object,
      default: () => ({}),
    },
    logs: {
      type: Array,
      default: () => [],
    },
    form: {
      type: Object,
      default: () => ({}),
    },
    currStatus: {
      type: [String, Number],
      default: '',
    },
    processId: {
      type: [String, Number],
      default: '',
    },
    priceId: {
      type: [String, Number],
      default: '',
    },
    planType: {
      type: String,
      default: 'BP',
    },
    currentNode: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    this.PLAN_TYPE = PLAN_TYPE;
    return {
      disabled: false,
    };
  },
  computed: {
    shapeOptions() {
      return this.$store.state.dictionary.dict['shape'] || {};
    },
    productionPlaceOptions() {
      return this.$store.state.dictionary.dict['production_place'] || {};
    },
    // modelOptions() {
    //   return this.$store.state.dictionary.dict['plan_detail_model'] || {};
    // },
    applicationOptions() {
      return this.$store.state.dictionary.dict['application'] || {};
    },
    factoryOptions() {
      return this.$store.state.dictionary.dict['factory_code'] || {};
    },
    categoryOptions() {
      return this.$store.state.dictionary.dict['category'] || {};
    },
    ...mapGetters(['spinning']),

    colIndex() {
      console.log(
        this.columns.findIndex(item => item.dataIndex === 'priceMonth0')
      );
      return this.columns.findIndex(item => item.dataIndex === 'priceMonth0');
    },
    totalAllIndex() {
      return this.dataSource.reduce((pre, cur, index) => {
        if (cur.id === 'totalKey') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          // customRender(t, r, index) {
          //   return parseInt(index) + 1;
          // },
          customRender: (t, r, index) => {
            if (this.totalAllIndex.includes(index)) {
              return {
                children: (
                  <div style="display: flex;justify-content: flex-start;">
                    汇总
                  </div>
                ),
                attrs: {
                  colSpan: this.colIndex,
                },
              };
            }
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: 'M+9关系ID',
          dataIndex: 'm9RelationId',
          key: 'm9RelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联RP关系ID',
          dataIndex: 'rpRelationId',
          key: 'rpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleRpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'rpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联BP关系ID',
          dataIndex: 'bpRelationId',
          key: 'bpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleBpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'bpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '厂别',
          dataIndex: 'factoryCode',
          key: 'factoryCode',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.factoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelInfoName',
          key: 'modelInfoName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          key: 'modelName',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '料号',
          dataIndex: 'materialCode',
          key: 'materialCode',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '生产地',
          width: 80,
          dataIndex: 'manufactureArea',
          key: 'manufactureArea',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.productionPlaceOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          key: 'application',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.applicationOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '模切比',
          width: 80,
          dataIndex: 'modelCutRate',
          key: 'modelCutRate',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '形态',
          dataIndex: 'appearance',
          key: 'appearance',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.shapeOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户项目',
          dataIndex: 'item',
          key: 'item',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '内部项目',
          dataIndex: 'innerItem',
          key: 'innerItem',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '类别',
          dataIndex: 'category',
          key: 'category',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.categoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '备注',
          width: 100,
          dataIndex: 'remark',
          key: 'remark',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
      ];
      if (this.dateArr.length) {
        this.dateArr.forEach((date, i) => {
          columns.push({
            align: 'center',
            title: date,
            dataIndex: `priceMonth${i}`,
            width: 180,
            ellipsis: true,
            children: [
              {
                align: 'center',
                title: 'BP',
                dataIndex: `bpPriceMonth${date}`,
                key: `bpPrice${date}`,
                width: 100,
              },
              {
                align: 'center',
                title: 'RP',
                dataIndex: `rpPriceMonth${date}`,
                key: `rpPrice${date}`,
                width: 100,
              },
              {
                align: 'center',
                title: 'M+9',
                dataIndex: `priceMonth${date}`,
                key: `price${date}`,
                width: 100,
              },
              {
                align: 'center',
                title: '最新价格',
                dataIndex: `newPriceMonth${date}`,
                key: `newPrice${date}`,
                width: 100,
                ellipsis: true,
                scopedSlots: {
                  customRender: `newPriceMonth${date}`,
                },
                customRender: (value, row, index) => {
                  // console.log(value, row, index,'value, row, index-===123')
                  // let totalKeys = Object.keys(row).filter((item) =>
                  //   item.includes(`${date}`)
                  // );

                  // // console.log(totalKeys,'totalKeys -===123')

                  // let isDisabled = !totalKeys.length

                  const children = (
                    <div>
                      <p-tooltip title={value}>
                        <InputTable
                          isEdit={this.isEdit}
                          isNewPrice={true}
                          value={value}
                          vOn:change={e =>
                            this.handleInputChange(
                              e,
                              value,
                              row,
                              index,
                              `newPriceMonth${date}`
                            )
                          }
                        />
                      </p-tooltip>
                    </div>
                  );
                  return {
                    children,
                  };
                },
              },
            ],
          });
        });
      }
      // console.log(columns);
      return columns;
    },

    titleName() {
      const type = '价格变更';
      const node = this.currentNode.label;
      const status =
        this.hasEdit && this.currentNode.key !== 'PriceStart'
          ? '待办'
          : undefined;
      return [type, node, status].filter(item => item).join('-');
    },
    // processId() {
    //   return this.detail?.plan?.processId;
    // },
    // hasEdit() {
    //   return this.form.createUserId ===this.form.handleUserId ? false : true;
    // }, record.createUserId === record.handleUserId
    filterButtons() {
      if (this.hasEdit) return this.footerButtons;
      return this.footerButtons.filter(item => !item.auth);
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (!val) return;
        // console.log('oooooooooo', this.detail);
        const plan = this.detail?.plan || {};
        const timeRanges = [plan.startTime, plan.endTime];
        // console.log('timeRanges: ', timeRanges);
        // this.form = {
        //   salesOrganization: plan.salesOrganization || '',
        //   serialNumber: plan.serialNumber || '',
        //   name: plan.name || '',
        //   startTime: timeRanges,
        //   deadlineTime: plan.deadlineTime || null,
        // };

        // 初版明细
        const planDetailList = this.detail?.planDetailList || [];
        this.planDetailList = transferDataDetail(planDetailList, timeRanges);

        // 终版明细
        const endPlanDetailList = this.detail?.endPlanDetailList || [];
        if (!endPlanDetailList.length) return;
        this.endPlanDetailList = transferDataDetail(
          endPlanDetailList,
          timeRanges
        );
      },
      immediate: true,
    },
  },
  methods: {
    customRender(children, index) {
      // console.log(index, str, 'children, index, row, key--------------------123')
      const attrs = {};
      if (this.totalAllIndex.includes(index)) {
        attrs.colSpan = 0;
      }
      return {
        children,
        attrs,
      };
    },
    handleInputChange(e, text, record, index, key) {
      if (e === '') {
        record[key] = null;
      }
      record[key] = e;
    },
    proessData(data) {
      return (data || []).map(item => {
        let price = this.dateVal('priceMonth', JSON.parse(item.price));
        let newPrice = this.dateVal('newPriceMonth', JSON.parse(item.newPrice));
        let bpPrice = this.dateVal('bpPriceMonth', JSON.parse(item.bpPrice));
        let rpPrice = this.dateVal('rpPriceMonth', JSON.parse(item.rpPrice));
        return {
          ...item,
          ...price,
          ...newPrice,
          ...bpPrice,
          ...rpPrice,
        };
      });
    },
    dateVal(val, typeObj) {
      let obj = {};
      for (let v in typeObj) {
        obj[`${val}${v}`] = typeObj[v];
      }
      return obj;
    },
  },
};
